package team.pwy.service;

import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import team.pwy.mapper.SeatMapper;
import team.pwy.pojo.entity.Seat;
import team.pwy.util.CreatJedis;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
@Transactional
public class SeatServiceImpl implements SeatService {
    @Resource
    private SeatMapper seatMapper;

    @Resource
    private WebSocketProcess webSocketProcess;

    private Jedis jedis;

    @Override
    public List<Seat> findByHallId(int sessionId) {
        return seatMapper.findByHallId(sessionId);
    }

    @Override
    public int updateByRC(int row, int column) {
        return seatMapper.updateByRC(row, column);
    }

    @Override
    public List<Seat> findByIds(List<Integer> ids) {
        return seatMapper.findByIds(ids);
    }

    @Override
    public List<Seat> findByStatus(int status) {
        return seatMapper.findByStatus(status);
    }

    @Override
    public void updateSeatStatus(int userId, int seatId, int status, int sessionId) {
        jedis = CreatJedis.getJedis();
        Set<String> seatIds = jedis.smembers("seat");

        // 判断set集合中是否包含seatId
        if (seatIds.contains(String.valueOf(seatId)))
            jedis.srem("seat", String.valueOf(seatId));
        else
            jedis.sadd("seat", String.valueOf(seatId));

        // 发送消息
        try {
            webSocketProcess.sendAllMessage(userId, seatId, status);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateSeatEnd(int userId, List<Integer> allSelectedSeatId, int sessionId) {

        jedis = CreatJedis.getJedis();
        // 移除用户选择的座位
        for (Integer selectSeatId : allSelectedSeatId)
            jedis.srem("seat", String.valueOf(selectSeatId));
        // 发送消息
        if (!allSelectedSeatId.isEmpty()) {
            for (Integer selectSeatId : allSelectedSeatId) {
                try {
                    webSocketProcess.sendAllMessage(userId, selectSeatId, 2);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    @Override
    public List<Integer> updateSeatFirst(int sessionId) {
        jedis = CreatJedis.getJedis();
        List<Integer> seatIds = new ArrayList<>();
        for (String seat : jedis.smembers("seat")) {
            seatIds.add(Integer.parseInt(seat));
        }
        return seatIds;
    }
}
